<template>
  <div class="view-fill">
    <div
      v-if="!assetDetailInfo.visible && !inventoryDataEntryInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :need-return="false"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('assetInventoryTask:printDetail')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="
              (infoList.data.status === 1 || infoList.data.status === 2) &&
              $permission('assetInventoryTask:inventory')
            "
            @click="inventoryTask"
            >盘点</el-button
          >
          <el-button
            v-if="
              infoList.data.status === 2 &&
              $permission('assetInventoryTask:complete')
            "
            @click="completeTask"
            >完成盘点</el-button
          >
          <el-button
            v-if="
              infoList.data.status === 4 &&
              infoList.data.planStatus !== 5 &&
              $permission('assetInventoryTask:revoke')
            "
            @click="revoke"
            >撤回</el-button
          >
        </template>
        <div id="table-list">
          <div class="model-panel">
            <div class="model-panel-title">
              <p>{{ $t('basic_information') }}</p>
            </div>
            <div class="model-panel-body">
              <basic-information :info="infoList" />
            </div>
          </div>

          <div id="table-box" class="model-panel">
            <div class="model-panel-title">
              <Tooltip :text="$t('detailInfo')" />
            </div>
            <div class="model-panel-body">
              <!-- 条件栏 -->
              <new-page-filter
                v-model:query="filterInfo.query.queryMap"
                :query-more-json="true"
                :filter-list="filterInfo.searchList"
                :filter-btn="filterInfo.searchBtn"
                :clear-type="clearType"
              >
              </new-page-filter>
              <div class="flex_full_item">
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :check-box="false"
                  :highlight-row="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :isDynamic="true"
                  @sortChange="sortChange"
                >
                  <template v-slot:col-preAssetName="scope">
                    <span
                      v-if="scope.row.inventoryStatus != '5'"
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.preAssetName }}</span
                    >
                    <span
                      v-else-if="scope.row.inventoryStatus == '5'"
                      class="slip-edit"
                      @click="showSurplusDetail(scope.row)"
                      >{{ scope.row.preAssetName }}</span
                    >
                    <span v-else>{{ scope.row.preAssetName }}</span>
                  </template>
                  <template v-slot:col-inventoryPercent="scope">
                    <span>{{ scope.row.inventoryPercent || 0 }}%</span>
                  </template>
                </page-table>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <!-- 数据录入 -->
    <OrderModify
      v-if="inventoryDataEntryInfo.visible"
      v-model:visible="inventoryDataEntryInfo.visible"
      :table-row-id="inventoryDataEntryInfo.id"
      :title="inventoryDataEntryInfo.title"
      @returnModify="returnModify"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <basic-information :info="surplusInfoList">
        <template v-slot:basic-assetUseDeptBusinessVOList>
          <dialog-table
            v-model:data="surplusInfoList.data.assetUseDeptBusinessVOList"
            :field-list="assetUseDeptTableInfo.fieldList"
            :pager="false"
            :check-box="false"
            :tab-index="true"
            :summary="false"
            :maxHeight="200"
          >
          </dialog-table>
        </template>
        <template v-slot:basic-assetCapitalSourceBusinessVOList>
          <dialog-table
            v-model:data="surplusInfoList.data.assetCapitalSourceBusinessVOList"
            :pager="false"
            :check-box="false"
            :tab-index="true"
            :summary="true"
            :summary-field-list="assetCapitalSourceTableInfo.summaryFieldList"
            :field-list="assetCapitalSourceTableInfo.fieldList"
            :maxHeight="200"
          >
          </dialog-table>
        </template>
      </basic-information>
    </page-dialog>
  </div>
</template>

<script setup>
import {
  getInventoryTaskOrderDetailCustomizeListAll,
  finishInventoryInventoryTaskOrder,
  getInventoryTaskOrderById,
  inventoryTaskOrderPrintOrder,
  inventoryTaskOrderExcelOrder,
  revokeInventoryTaskOrder,
  getInventorySurplusRecord,
} from '@/api/asset'
import { getCustomizeSetting } from '@/api/customize'
import { getCoreCodeStatus } from '@/api/core'
import { fatchTemplateByCode } from '@/api/base'
import { orderOpAffairAll } from '@/api/affair'
import OrderModify from './modify.vue'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'tableRowId'])
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRowId,
      },
    },
    queryParams: {},
  },
  data: {
    selectModeOption: proxy.$store.state.permission.dict['selectMode'] || [],
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
})

const infoList = ref({
  data: {},
  fieldList: [
    { label: '任务单号', value: 'orderNo' },
    { label: '状态', value: 'statusValue' },
    {
      label: '盘点位置',
      value: 'inventoryLocationValue',
    },
    { label: '任务负责人', value: 'taskResponseUserName' },
    { label: '盘点人', value: 'taskInventoryUserName' },
    { label: '任务进度', value: 'inventoryPercent', type: 'progress' },
    { label: '应盘', value: 'inventoryQty' },
    { label: '待盘', value: 'pendInventoryQty' },
    { label: '相符', value: 'matchQty' },
    { label: '盘盈', value: 'surplusQty' },
    { label: '盘亏', value: 'lossQty' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '计划开始日期', value: 'planStartDate' },
    { label: '计划结束日期', value: 'planEndDate' },
  ],
})
const surplusInfoList = ref({
  data: {},
  fieldList: [
    {
      label: '资产名称',
      value: 'assetName',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      show: true,
    },
    {
      label: '规格',
      value: 'standard',
      show: true,
    },
    {
      label: '厂家名称',
      value: 'brandName',
    },
    {
      label: '品牌',
      value: 'mark',
    },
    {
      label: '医疗器械分类目录',
      value: 'deviceTypeValue',
    },
    {
      label: '临时采购',
      value: 'temporaryPurchValue',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '产地',
      value: 'originPlace',
    },
    {
      label: '使用状态',
      value: 'useStatusValue',
    },
    {
      label: '仓库',
      value: 'depotName',
      show: computed(() => {
        return infoList.value.data.inventoryLocation == 2
      }),
    },
    {
      label: '管理部门',
      value: 'manageDeptName',
    },
    {
      label: '增加方式',
      value: 'increaseTypeValue',
    },
    {
      label: '计量单位',
      value: 'unitName',
    },
    {
      label: '原值',
      value: 'primitiveOriginalAmount',
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
    },
    {
      label: '设备标识',
      value: 'assetMarkValue',
    },
    {
      label: '使用人',
      value: 'useUserName',
      show: computed(() => {
        return infoList.value.data.inventoryLocation == 1
      }),
    },

    {
      label: '存放地点',
      value: 'location',
    },
    {
      label: '备注',
      value: 'remark',
    },
    {
      label: '使用部门',
      value: 'assetUseDeptBusinessVOList',
      type: 'slot',
      show: computed(() => {
        return infoList.value.data.inventoryLocation == 1
      }),
      className: 'not-br',
    },
    {
      label: '资金来源',
      value: 'assetCapitalSourceBusinessVOList',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
//资金来源表格
const assetCapitalSourceTableInfo = ref({
  data: [],
  summaryFieldList: [
    { value: 'amount', formatter: proxy.$fn.TripartiteMethodAsset },
  ],
  fieldList: [
    {
      label: '资金来源',
      value: 'sourceName',
    },
    {
      label: '金额',
      value: 'amount',
    },
  ],
})
const assetUseDeptTableInfo = ref({
  data: [],
  fieldList: [
    { label: '部门', value: 'useDeptName' },
    {
      label: '占比(%)',
      value: 'rate',
      labelTip: '总值100%',
    },
  ],
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 48,
    orderId: props.tableRowId,
    sort: 'operate_time desc',
  },
})
// 表格相关
const tableInfo = ref({
  ref: null,
  refresh: 1,
  initCurpage: 1,
  copyData: [],
  isSysGroup: true,
  data: [],
  groupList: [], //合并项
  selections: [],
  fieldList: [],
})

const fullInfo = ref({
  btnList: [
    /*{
      label: '打印',
      event: print,
      show: proxy.$permission('assetInventoryTask:printDetail'),
    },*/
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('assetInventoryTask:excel'),
    },
    { value: 'button', type: 'slot' },
    { label: '返回', event: returnBack, show: true },
  ],
})
const dialogInfo = ref({
  visible: false,
  title: '盘盈详情',
  btLoading: false,
  type: '',
  msg: '',
  width: '1000px',
  flag: 'page',
  btList: [{ label: '关闭', event: handleClose, show: true }],
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const inventoryDataEntryInfo = ref({
  visible: false,
  title: '盘点录入',
  id: '',
})
const clearType = ref(true)

const obj = ref({
  filePath: {
    label: '盘点图片',
    value: 'filePath',
    type: 'showImage',
    show: false,
    hidden: true,
  },
  surplusStatusValue: {
    label: '状态',
    value: 'surplusStatusValue',
    asValue: 'surplusStatus',
    componentType: 'select-model',
    code: 'asset_inventory_surplus_status',
    show: false,
    hidden: true,
  },
  inventoryPercent: {
    label: '盘点进度',
    value: 'inventoryPercent',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
getCustomize()
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

function handleClose() {
  dialogInfo.value.visible = false
}
function returnModify() {
  getCustomize()
}
function inventoryTask() {
  //盘点
  inventoryDataEntryInfo.value.visible = true
  inventoryDataEntryInfo.value.id = props.tableRowId
}
function revoke() {
  //撤回
  revokeInventoryTaskOrder([props.tableRowId]).then((res) => {
    if (res && res.success) {
      getList()
      getMain()
    }
  })
}

function completeTask() {
  //完成盘点
  finishInventoryInventoryTaskOrder(props.tableRowId).then((res) => {
    if (res && res.success) {
      getList()
      getMain()
    }
  })
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function showSurplusDetail(row) {
  getInventorySurplusRecord({ taskOrderDetailId: row.id }).then((res) => {
    if (res && res.success) {
      getStatus()
      dialogInfo.value.visible = true
      surplusInfoList.value.data = res.data
    }
  })
}
function getStatus() {
  getCoreCodeStatus({ codeType: '7' }).then((res) => {
    surplusInfoList.value.fieldList.forEach((item) => {
      if (item.value === 'assetCode') {
        item.show = !res.data
      }
    })
  })
}
function getList() {
  getInventoryTaskOrderDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    }
  )
}
// 搜索
function search() {
  ////搜索
  getList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function returnBack() {
  //返回
  showDialog.value = false
  emits('returnBack')
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'inventoryPlanOrderDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: props.tableRowId,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: props.tableRowId,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getMain() {
  getInventoryTaskOrderById(props.tableRowId).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      infoList.value.data = data
    }
  })
}
function exportExcel() {
  let query = proxy.$fn.deepClone(filterInfo.value.query)
  inventoryTaskOrderExcelOrder(query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetManageAssetInventoryTaskDetais-com.slip.spd.entity.vo.asset.AssetInventoryTaskOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      if (props.tableRowId) {
        getMain()
        getList()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.el-tabs__header) {
  padding: 0 2px !important;
  box-sizing: border-box;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px !important;
}
</style>
